import request from './config';

interface CreateFolderParams {
  folderName: string;
  parentId: string | null;
  userId: string;
}

// 创建文件夹
export const createFolder = (params: CreateFolderParams) => {
  return request.post('/api/folders/create', params);
};

// 获取根文件夹内容
export const getRootFolders = (userId: string) => {
  return request.get(`/api/folders/root/${userId}`);
};

// 获取文件夹内容
export const getFolderContents = (folderId: string | null, userId: string) => {
  return request.get(`/api/folders/${folderId || 'root'}/${userId}`);
};

// 重命名文件夹
export const renameFolder = (folderId: string, newName: string, userId: string) => {
  return request.put(`/api/folders/${folderId}/rename`, { newName, userId });
};

// 删除文件夹
export const deleteFolder = (folderId: string, userId: string) => {
  return request.delete(`/api/folders/${folderId}`, { data: { userId } });
};

// 移动文件夹
export const moveFolder = (folderId: string, newParentId: string | null, userId: string) => {
  return request.put(`/api/folders/${folderId}/move`, { newParentId, userId });
};

// 下载文件夹
export const downloadFolder = (folderId: string, userId: string) => {
  return request.get(`/api/folders/download/${folderId}/${userId}`, {
    responseType: 'blob'
  });
};

// 上传文件夹
export const uploadFolder = async (files: File[], userId: string, parentFolderId: string | null = null) => {
  const formData = new FormData();
  
  // 添加用户ID和父文件夹ID
  formData.append('userId', userId);
  if (parentFolderId) {
    formData.append('parentFolderId', parentFolderId);
  }

  // 分片上传
  const chunkSize = 5 * 1024 * 1024; // 5MB
  for (const file of files) {
    const totalChunks = Math.ceil(file.size / chunkSize);
    for (let i = 0; i < totalChunks; i++) {
      const chunk = file.slice(i * chunkSize, (i + 1) * chunkSize);
      formData.append('files', chunk, file.name);
      formData.append('chunkIndex', i.toString());
      formData.append('totalChunks', totalChunks.toString());
      
      // 上传每个分片
      await request.post('/api/folders/upload-folder', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
    }
  }
};